package com.example.redisdemo;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author Jonathan
 * 2021/5/28 19:11
 */
@Slf4j
@Service
public class RedisLock {

    private static final ConcurrentHashMap<String, RLock> map = new ConcurrentHashMap<>();
    private final RedissonClient redissonClient;

    public RedisLock(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    public boolean tryLock(String key, int waitSeconds, int leaseSeconds) {
        RLock lock = redissonClient.getLock(key);
        boolean hasLock = false;
        try {
            hasLock = lock.tryLock(waitSeconds, leaseSeconds, TimeUnit.SECONDS);
            if (hasLock) {
                map.put(key, lock);
            }
        } catch (InterruptedException e) {
            log.error(e.getLocalizedMessage());
        }
        return hasLock;
    }

    public void unlock(String key) {
        RLock lock = map.remove(key);
        if (lock != null && lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }
}
